package com.xmzs.midjourney.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xmzs.common.core.exception.ServiceException;
import com.xmzs.common.core.utils.MapstructUtils;
import com.xmzs.common.core.utils.StringUtils;
import com.xmzs.common.core.utils.file.FileUtils;
import com.xmzs.common.mybatis.core.page.TableDataInfo;
import com.xmzs.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xmzs.midjourney.constant.MidjourneyConstant;
import com.xmzs.midjourney.domain.MjRoom;
import com.xmzs.midjourney.domain.MjServer;
import com.xmzs.midjourney.domain.bo.MjRoomBo;
import com.xmzs.midjourney.domain.request.MjConvertRequest;
import com.xmzs.midjourney.domain.request.MjDescribeRequest;
import com.xmzs.midjourney.domain.request.MjImagineRequest;
import com.xmzs.midjourney.domain.vo.MjRoomVo;
import com.xmzs.midjourney.enums.MessageTypeEnum;
import com.xmzs.midjourney.enums.MidjourneyMsgActionEnum;
import com.xmzs.midjourney.enums.MidjourneyMsgStatusEnum;
import com.xmzs.midjourney.handler.MidjourneyRoomMsgHandler;
import com.xmzs.midjourney.handler.MidjourneyTaskQueueHandler;
import com.xmzs.midjourney.handler.MjServerHandler;
import com.xmzs.midjourney.service.DiscordSendService;
import com.xmzs.midjourney.service.DiscordService;
import com.xmzs.midjourney.service.IMjRoomService;
import com.xmzs.midjourney.util.MjRoomMessageUtil;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.xmzs.midjourney.domain.bo.MjRoomMsgBo;
import com.xmzs.midjourney.domain.vo.MjRoomMsgVo;
import com.xmzs.midjourney.domain.MjRoomMsg;
import com.xmzs.midjourney.mapper.MjRoomMsgMapper;
import com.xmzs.midjourney.service.IMjRoomMsgService;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * Midjourney 创作记录Service业务层处理
 *
 * @author lixg
 * @date 2023-08-09
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class MjRoomMsgServiceImpl implements IMjRoomMsgService {

    private final MjRoomMsgMapper baseMapper;
    @Resource
    private DiscordService discordService;

    @Resource
    private MidjourneyTaskQueueHandler midjourneyTaskQueueHandler;

    @Resource
    private MjServerHandler mjServerHandler;
    @Resource
    private IMjRoomService roomService;

    /**
     * 查询Midjourney 创作记录
     */

    public MjRoomMsg queryById(Long id){

        return getOne(new LambdaQueryWrapper<MjRoomMsg>().eq(MjRoomMsg::getId,id));
    }

    /**
     * 查询Midjourney 创作记录列表
     */
    @Override
    public TableDataInfo<MjRoomMsgVo> queryPageList(MjRoomMsgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MjRoomMsg> lqw = buildQueryWrapper(bo);
        Page<MjRoomMsgVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询Midjourney 创作记录列表
     */
    @Override
    public List<MjRoomMsgVo> queryList(MjRoomMsgBo bo) {
        LambdaQueryWrapper<MjRoomMsg> lqw = buildQueryWrapper(bo);
        lqw.eq(MjRoomMsg::getUserId, StpUtil.getLoginId());
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public Long selectCount(Wrapper<MjRoomMsg> queryWrapper) {
        return baseMapper.selectCount(queryWrapper);

    }

    @Override
    public MjRoomMsg getOne(Wrapper<MjRoomMsg> queryWrapper) {

        return baseMapper.selectOne(queryWrapper);
    }

    private LambdaQueryWrapper<MjRoomMsg> buildQueryWrapper(MjRoomMsgBo bo) {
        LambdaQueryWrapper<MjRoomMsg> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getResponseContent()), MjRoomMsg::getResponseContent, bo.getResponseContent());
        lqw.eq(bo.getStatus() != null, MjRoomMsg::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增Midjourney 创作记录
     */
    @Override
    public Boolean insertByBo(MjRoomMsgBo bo) {
        MjRoomMsg add = MapstructUtils.convert(bo, MjRoomMsg.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改Midjourney 创作记录
     */
    @Override
    public Boolean updateByBo(MjRoomMsgBo bo) {
        MjRoomMsg update = MapstructUtils.convert(bo, MjRoomMsg.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }
    @Override
    public Boolean update(MjRoomMsg entity, Wrapper<MjRoomMsg> updateWrapper) {
        return baseMapper.update(entity,updateWrapper) > 0;
    }
    @Override
    public List<MjRoomMsg> queryList(Wrapper<MjRoomMsg> queryWrapper){
        return baseMapper.selectList(queryWrapper);

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MjRoomMsg entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除Midjourney 创作记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void imagine(MjImagineRequest imagineRequest) {
        // 检查是否可以操作
        MidjourneyRoomMsgHandler.checkCanOperate(imagineRequest.getRoomId());

        // 这两个 id 按先后顺序生成，保证在表里的顺序也是有先后的
        // 生成问题的消息 id
        long questionMessageId = IdWorker.getId();
        // 生成回答消息的 id
        long answerMessageId = IdWorker.getId();
        MjRoomVo mjRoomVo = getMjRoomVoByUserId();
        //通过服务器ID获取服务器配置信息
        MjServer midjourneyProperties = mjServerHandler.getServerByGuildId(mjRoomVo.getMjGuildId());

        // 问题消息创建插入
        MjRoomMsgBo questionMessage = new MjRoomMsgBo();
        questionMessage.setId(questionMessageId);
        questionMessage.setMjRoomId(imagineRequest.getRoomId());

        questionMessage.setUserId(String.valueOf(StpUtil.getLoginId()));
        questionMessage.setType(MessageTypeEnum.QUESTION);
        questionMessage.setPrompt(imagineRequest.getPrompt());
        // 组装最终的 prompt
        questionMessage.setFinalPrompt("[".concat(String.valueOf(answerMessageId)).concat("] ").concat(questionMessage.getPrompt()));
        questionMessage.setAction(MidjourneyMsgActionEnum.IMAGINE);
        questionMessage.setStatus(MidjourneyMsgStatusEnum.SYS_SUCCESS);
        questionMessage.setDiscordChannelId(midjourneyProperties.getChannelId());
        questionMessage.setIsDeleted(false);
        questionMessage.setTemplateId("0");
        questionMessage.setGuildId(mjRoomVo.getMjGuildId());
        questionMessage.setCreateTime(new DateTime());
        questionMessage.setUpdateTime(questionMessage.getCreateTime());
        insertByBo(questionMessage);

        // 初始化回答消息
        MjRoomMsgBo answerMessage = new MjRoomMsgBo();
        answerMessage.setId(answerMessageId);
        answerMessage.setMjRoomId(questionMessage.getMjRoomId());
        answerMessage.setPrompt(questionMessage.getPrompt());
        answerMessage.setFinalPrompt(questionMessage.getFinalPrompt());
        answerMessage.setAction(MidjourneyMsgActionEnum.IMAGINE);
        answerMessage.setUUseBit(0);

        // 校验敏感词 TODO 暂时不实现
//        boolean isCheckPromptPass = checkPromptContent(questionMessage, answerMessage);
//        if (!isCheckPromptPass) {
//            return;
//        }

        // 创建回答消息
        createAnswerMessage(answerMessage, midjourneyProperties, () -> discordService.imagine(answerMessage.getFinalPrompt(), midjourneyProperties));
    }

    /**
     * 通过用户ID查询用户对应的会话ID
     * @return
     */
    private MjRoomVo getMjRoomVoByUserId() {
        String userId = String.valueOf(StpUtil.getLoginId());
        //通过userId查询到roomId
        MjRoomBo mjRoomBo = new MjRoomBo();
        mjRoomBo.setUserId(userId);
        List<MjRoomVo> mjRoomVoList = roomService.queryList(mjRoomBo);
        //通过roomid获取服务器ID
        return mjRoomVoList.get(0);
    }

    @Override
    public void upscale(MjConvertRequest convertRequest) {
        // 检查是否可以操作
        MidjourneyRoomMsgHandler.checkCanOperate(convertRequest.getRoomId());
        //通过roomid获取服务器ID
        MjRoomVo mjRoomVo = getMjRoomVoByUserId();
        //通过服务器ID获取服务器配置信息
        MjServer midjourneyProperties = mjServerHandler.getServerByGuildId(mjRoomVo.getMjGuildId());
        // 获取原消息
        MjRoomMsg parentRoomMidjourneyMsgDO = getOne(new LambdaQueryWrapper<MjRoomMsg>().eq(MjRoomMsg::getId, convertRequest.getMsgId())
            .eq(MjRoomMsg::getMjRoomId, convertRequest.getRoomId())
            .eq(MjRoomMsg::getUserId, String.valueOf(StpUtil.getLoginId())));
        // 检查是否可以 upscale

        MidjourneyRoomMsgHandler.checkCanUpscale(parentRoomMidjourneyMsgDO, convertRequest.getIndex(), midjourneyProperties);

        // 这两个 id 按先后顺序生成，保证在表里的顺序也是有先后的
        // 生成问题的消息 id
        long questionMessageId = IdWorker.getId();
        // 生成回答消息的 id
        long answerMessageId = IdWorker.getId();

        // 问题消息创建插入
        MjRoomMsgBo questionMessage = new MjRoomMsgBo();
        questionMessage.setId(questionMessageId);
        questionMessage.setMjRoomId(parentRoomMidjourneyMsgDO.getMjRoomId());
        questionMessage.setUserId(parentRoomMidjourneyMsgDO.getUserId());
        questionMessage.setTemplateId("0");
        questionMessage.setGuildId(mjRoomVo.getMjGuildId());
        questionMessage.setType(MessageTypeEnum.QUESTION);
        questionMessage.setPrompt(parentRoomMidjourneyMsgDO.getPrompt());
        questionMessage.setFinalPrompt(parentRoomMidjourneyMsgDO.getFinalPrompt());
        questionMessage.setUvParentId(parentRoomMidjourneyMsgDO.getId().intValue());
        questionMessage.setUvIndex(convertRequest.getIndex());
        questionMessage.setDiscordMessageId(parentRoomMidjourneyMsgDO.getDiscordMessageId());
        questionMessage.setAction(MidjourneyMsgActionEnum.UPSCALE);
        questionMessage.setStatus(MidjourneyMsgStatusEnum.SYS_SUCCESS);
        questionMessage.setIsDeleted(false);
        questionMessage.setTemplateId("0");
        questionMessage.setGuildId(mjRoomVo.getMjGuildId());
        questionMessage.setCreateTime(new DateTime());
        questionMessage.setUpdateTime(questionMessage.getCreateTime());
        insertByBo(questionMessage);

        // 初始化回答消息
        MjRoomMsgBo answerMessage = new MjRoomMsgBo();
        answerMessage.setId(answerMessageId);
        answerMessage.setMjRoomId(questionMessage.getMjRoomId());
        answerMessage.setPrompt(questionMessage.getPrompt());
        answerMessage.setFinalPrompt(questionMessage.getFinalPrompt());
        answerMessage.setAction(MidjourneyMsgActionEnum.UPSCALE);
        answerMessage.setUvParentId(parentRoomMidjourneyMsgDO.getId().intValue());
        answerMessage.setUvIndex(convertRequest.getIndex());
        // 这里先赋值，因为回调监听没有可以赋值的地方
        answerMessage.setDiscordStartTime(new Date());

        // 创建回答消息
        createAnswerMessage(answerMessage, midjourneyProperties,
            () -> discordService.upscale(parentRoomMidjourneyMsgDO.getDiscordMessageId(),
                answerMessage.getUvIndex(),
                MidjourneyRoomMsgHandler.getDiscordMessageHash(parentRoomMidjourneyMsgDO.getDiscordImageUrl()),
                midjourneyProperties));
    }

    @Override
    public void variation(MjConvertRequest convertRequest) {
        // 检查是否可以操作
        MidjourneyRoomMsgHandler.checkCanOperate(convertRequest.getRoomId());

        // 获取原消息
        MjRoomMsg parentRoomMidjourneyMsgDO = getOne(new LambdaQueryWrapper<MjRoomMsg>().eq(MjRoomMsg::getId, convertRequest.getMsgId())
            .eq(MjRoomMsg::getMjRoomId, convertRequest.getRoomId())
            .eq(MjRoomMsg::getUserId,String.valueOf(StpUtil.getLoginId())));
        // 检查是否可以 variation
        //通过roomid获取服务器ID
        MjRoomVo mjRoomVo = getMjRoomVoByUserId();
        //通过服务器ID获取服务器配置信息
        MjServer midjourneyProperties = mjServerHandler.getServerByGuildId(mjRoomVo.getMjGuildId());
        MidjourneyRoomMsgHandler.checkCanVariation(parentRoomMidjourneyMsgDO, midjourneyProperties);

        // 这两个 id 按先后顺序生成，保证在表里的顺序也是有先后的
        // 生成问题的消息 id
        long questionMessageId = IdWorker.getId();
        // 生成回答消息的 id
        long answerMessageId = IdWorker.getId();

        // 问题消息创建插入
        MjRoomMsgBo questionMessage = new MjRoomMsgBo();
        questionMessage.setId(questionMessageId);
        questionMessage.setMjRoomId(parentRoomMidjourneyMsgDO.getMjRoomId());
        questionMessage.setUserId(parentRoomMidjourneyMsgDO.getUserId());
        questionMessage.setType(MessageTypeEnum.QUESTION);
        questionMessage.setPrompt(parentRoomMidjourneyMsgDO.getPrompt());
        questionMessage.setFinalPrompt(parentRoomMidjourneyMsgDO.getFinalPrompt());
        questionMessage.setUvParentId(parentRoomMidjourneyMsgDO.getId().intValue());
        questionMessage.setUvIndex(convertRequest.getIndex());
        questionMessage.setDiscordMessageId(parentRoomMidjourneyMsgDO.getDiscordMessageId());
        questionMessage.setAction(MidjourneyMsgActionEnum.VARIATION);
        questionMessage.setStatus(MidjourneyMsgStatusEnum.SYS_SUCCESS);
        questionMessage.setIsDeleted(false);
        questionMessage.setTemplateId("0");
        questionMessage.setGuildId(mjRoomVo.getMjGuildId());
        questionMessage.setCreateTime(new DateTime());
        questionMessage.setUpdateTime(questionMessage.getCreateTime());
        insertByBo(questionMessage);

        // 初始化回答消息
        MjRoomMsgBo answerMessage = new MjRoomMsgBo();
        answerMessage.setId(answerMessageId);
        answerMessage.setMjRoomId(questionMessage.getMjRoomId());
        answerMessage.setPrompt(questionMessage.getPrompt());
        answerMessage.setFinalPrompt(questionMessage.getFinalPrompt());
        answerMessage.setAction(MidjourneyMsgActionEnum.VARIATION);
        answerMessage.setUvParentId(parentRoomMidjourneyMsgDO.getId().intValue());
        answerMessage.setUvIndex(convertRequest.getIndex());
        answerMessage.setDiscordStartTime(new Date());

        // 创建回答消息
        createAnswerMessage(answerMessage, midjourneyProperties,
            () -> discordService.variation(parentRoomMidjourneyMsgDO.getDiscordMessageId(),
                answerMessage.getUvIndex(),
                MidjourneyRoomMsgHandler.getDiscordMessageHash(parentRoomMidjourneyMsgDO.getDiscordImageUrl()),
                midjourneyProperties));
    }

    @Override
    public void describe(MjDescribeRequest describeRequest) {

        // 这两个 id 按先后顺序生成，保证在表里的顺序也是有先后的
        // 生成问题的消息 id
        long questionMessageId = IdWorker.getId();
        // 生成回答消息的 id
        long answerMessageId = IdWorker.getId();

        MultipartFile multipartFile = describeRequest.getFile();
        // 新原始文件名：前缀 + 消息 id + 后缀
        String newOriginalFileName = MidjourneyConstant.DESCRIBE_ORIGINAL_FILE_PREFIX + answerMessageId + StrPool.DOT + FileUtils.getFileExtension(multipartFile.getOriginalFilename());
        // 保存文件
        FileUtils.downloadFromMultipartFile(multipartFile, newOriginalFileName);

        //通过roomid获取服务器ID
        MjRoomVo mjRoomVo = getMjRoomVoByUserId();
        //通过服务器ID获取服务器配置信息
        MjServer midjourneyProperties = mjServerHandler.getServerByGuildId(mjRoomVo.getMjGuildId());

        // 判断文件大小
        if (multipartFile.getSize() > midjourneyProperties.getMaxFileSize()) {
            int maxMbFileSize = midjourneyProperties.getMaxFileSize().intValue() / 1024 / 1024;
            log.warn("Midjourney 业务异常，用户 id：{}，房间 id：{}，describe 文件大小为{}MB，超过{}MB限制", StpUtil.getLoginId(), describeRequest.getRoomId(), multipartFile.getSize(), maxMbFileSize);
            throw new ServiceException(StrUtil.format("文件大小超过{}MB限制", maxMbFileSize));
        }

        // 判断文件后缀是否符合
        if (!StrUtil.equalsAnyIgnoreCase(multipartFile.getContentType(), MidjourneyConstant.IMAGE_JPEG, MidjourneyConstant.IMAGE_PNG)) {
            log.warn("Midjourney 业务异常，用户 id：{}，房间 id：{}，describe 文件大小格式为 {} 错误", StpUtil.getLoginId(), describeRequest.getRoomId(), multipartFile.getContentType());
            throw new ServiceException("文件格式不符合要求，只能是 jpg 或 png 格式");
        }

        // TODO 图片审核

        // 上传图片
        Pair<Boolean, String> uploadResponsePair = discordService.uploadImage(newOriginalFileName, multipartFile, midjourneyProperties);
        if (!uploadResponsePair.getKey()) {
            throw new ServiceException(uploadResponsePair.getValue());
        }

        // 上面的操作应该没有并发限制，所以上面的上传图片操作就不考虑队列限制

        String discordUploadFileName = uploadResponsePair.getValue();
        // 检查是否有正在处理的任务
        MidjourneyRoomMsgHandler.checkExistProcessingTask();

        // 下载压缩图片
        String compressedImageFileName = MjRoomMessageUtil.downloadCompressedImage(newOriginalFileName, answerMessageId);

        // 问题消息创建插入
        MjRoomMsgBo questionMessage = new MjRoomMsgBo();
        questionMessage.setId(questionMessageId);
        questionMessage.setMjRoomId(describeRequest.getRoomId());
        questionMessage.setUserId(String.valueOf(StpUtil.getLoginId()));
        questionMessage.setType(MessageTypeEnum.QUESTION);
        questionMessage.setOriginalImageName(newOriginalFileName);
        questionMessage.setCompressedImageName(compressedImageFileName);
        questionMessage.setDiscordImageUrl(discordUploadFileName);
        questionMessage.setAction(MidjourneyMsgActionEnum.DESCRIBE);
        questionMessage.setStatus(MidjourneyMsgStatusEnum.SYS_SUCCESS);
        questionMessage.setDiscordChannelId(midjourneyProperties.getChannelId());
        questionMessage.setIsDeleted(false);
        questionMessage.setTemplateId("0");
        questionMessage.setGuildId(mjRoomVo.getMjGuildId());
        questionMessage.setCreateTime(new DateTime());
        questionMessage.setUpdateTime(questionMessage.getCreateTime());
        insertByBo(questionMessage);

        // 初始化回答消息
        MjRoomMsgBo answerMessage = new MjRoomMsgBo();
        answerMessage.setId(answerMessageId);
        answerMessage.setMjRoomId(questionMessage.getMjRoomId());
        answerMessage.setOriginalImageName(newOriginalFileName);
        answerMessage.setCompressedImageName(compressedImageFileName);
        answerMessage.setDiscordImageUrl(discordUploadFileName);
        answerMessage.setAction(MidjourneyMsgActionEnum.DESCRIBE);
        answerMessage.setDiscordStartTime(new Date());
        answerMessage.setUUseBit(0);

        // 创建回答消息
        createAnswerMessage(answerMessage, midjourneyProperties, () -> discordService.describe(answerMessage.getDiscordImageUrl(), midjourneyProperties));
    }

    /**
     * 创建回答消息
     *
     * @param answerMessage        回答消息
     * @param midjourneyProperties Midjourney 配置
     * @param discordSendService   discord 发送服务接口
     */
    private void createAnswerMessage(MjRoomMsgBo answerMessage, MjServer midjourneyProperties, DiscordSendService discordSendService) {
        // 填充公共字段
        answerMessage.setUserId(String.valueOf(StpUtil.getLoginId()));
        answerMessage.setType(MessageTypeEnum.ANSWER);
        answerMessage.setDiscordChannelId(midjourneyProperties.getChannelId());
        answerMessage.setIsDeleted(false);
        answerMessage.setGuildId(midjourneyProperties.getGuildId());

        // 创建任务并返回回答的状态
        MidjourneyMsgStatusEnum answerStatus = midjourneyTaskQueueHandler.pushNewTask(answerMessage.getId(), midjourneyProperties);
        // 达到队列上限
        if (answerStatus == MidjourneyMsgStatusEnum.SYS_MAX_QUEUE) {
            answerMessage.setResponseContent(StrUtil.format("当前排队任务为 {} 条，已经达到上限，请稍后再试", midjourneyProperties.getMaxWaitQueueSize()));
        }
        answerMessage.setStatus(answerStatus);
        answerMessage.setCreateTime(new DateTime());
        answerMessage.setUpdateTime(answerMessage.getCreateTime());
        insertByBo(answerMessage);

        // 等待接收状态，此时可以调用 discord 接口
        if (answerStatus == MidjourneyMsgStatusEnum.MJ_WAIT_RECEIVED) {
            Pair<Boolean, String> resultPair = discordSendService.sendRequest();
            // 调用失败的情况，应该是少数情况，这里不重试
            if (!resultPair.getKey()) {
                answerMessage.setStatus(MidjourneyMsgStatusEnum.SYS_SEND_MJ_REQUEST_FAILURE);
                answerMessage.setResponseContent("系统异常，直接调用 discord 接口失败，请稍后再试");
                answerMessage.setFailureReason(resultPair.getValue());
                answerMessage.setUpdateTime(new DateTime());
                updateByBo(answerMessage);

                // 结束执行中任务
                midjourneyTaskQueueHandler.finishExecuteTask(answerMessage.getId());
            }
        }
    }



    /**
     * 校验 prompt 内容是否合规
     *
     * @param questionMessage 问题消息
     * @param answerMessage   回答消息
     * @return 是否合规
     */
    private boolean checkPromptContent(MjRoomMsgBo questionMessage, MjRoomMsgBo answerMessage,MjRoom room) {
        // 填充公共字段
        answerMessage.setUserId(String.valueOf(StpUtil.getLoginId()));
        answerMessage.setType(MessageTypeEnum.ANSWER);
        answerMessage.setStatus(MidjourneyMsgStatusEnum.SYS_FAILURE);
        answerMessage.setDiscordChannelId(null);
        answerMessage.setIsDeleted(false);

        // 获取所有配置项
//        Map<MidjourneyCellConfigCodeEnum, DataWrapper> cellConfigCodeMap = midjourneyCellConfigStrategy.getCellConfigMap();

        // 检查本地敏感词校验是否启用 TODO 暂时不实现
//        if (room.getEnabledLocalSensitiveWord()) {
//            List<String> sensitiveWords = SensitiveWordHandler.checkWord(questionMessage.getPrompt());
//            if (CollectionUtil.isNotEmpty(sensitiveWords)) {
//                answerMessage.setResponseContent(StrUtil.format("发送失败，包含敏感词{}", sensitiveWords));
//                answerMessage.setFailureReason("本地敏感词库：".concat(answerMessage.getResponseContent()));
//                insertByBo(answerMessage);
//                return false;
//            }
//        }

        // 检查百度敏感词校验是否启用 TODO 暂时不实现
//        if (room.getEnabledBaiduAip()) {
//            Pair<Boolean, String> checkTextPassResultPair = BaiduAipHandler.isCheckTextPass(String.valueOf(answerMessage.getId()), questionMessage.getPrompt());
//            if (!checkTextPassResultPair.getKey()) {
//                // 填充公共字段
//                answerMessage.setResponseContent("存在不合规内容，请修改内容");
//                answerMessage.setFailureReason(checkTextPassResultPair.getValue());
//                insertByBo(answerMessage);
//                return false;
//            }
//        }

        return true;
    }
}
